package com.example.wanandroid.activity.main.home

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.wanandroid.entity.article.Article
import com.example.wanandroid.entity.article.ArticleData
import com.example.wanandroid.entity.banner.BannerData
import com.example.wanandroid.retrofit.RetrofitUtil
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class HomeViewModel : ViewModel() {
    val errorLiveData = MutableLiveData<String>()
    val bannerLiveData = MutableLiveData<BannerData>()
    var page = 0
    val articles = ArrayList<Article>()
    val articlesLiveData = MutableLiveData<List<Article>>()

    fun getBannerData(){
        RetrofitUtil.wanAndroidApi.getBannerData().enqueue(object : Callback<BannerData> {
            override fun onResponse(call: Call<BannerData>, response: Response<BannerData>) {
                bannerLiveData.value = response.body()
            }

            override fun onFailure(call: Call<BannerData>, t: Throwable) {
                errorLiveData.value = t.message
            }

        })
    }

    fun getArticleData(){
        page = 0
        RetrofitUtil.wanAndroidApi.getArticleData(page).enqueue(object :Callback<ArticleData>{
            override fun onResponse(call: Call<ArticleData>, response: Response<ArticleData>) {
                val _articles = response.body()?.data?.datas
                if (_articles != null) {
                    articles.clear()
                    articles.addAll(_articles)
                    articlesLiveData.value = articles
                }
            }

            override fun onFailure(call: Call<ArticleData>, t: Throwable) {
                errorLiveData.value = t.message
            }

        })
    }

    fun getMoreArticleData(){
        page++
        RetrofitUtil.wanAndroidApi.getArticleData(page).enqueue(object :Callback<ArticleData>{
            override fun onResponse(call: Call<ArticleData>, response: Response<ArticleData>) {
                val _articles = response.body()?.data?.datas
                if (_articles != null) {
                    articles.addAll(_articles)
                    articlesLiveData.value = articles
                }
            }

            override fun onFailure(call: Call<ArticleData>, t: Throwable) {
                errorLiveData.value = t.message
            }

        })
    }

}